/*
 * @Author: your name
 * @Date: 2021-02-20 12:57:24
 * @LastEditTime: 2022-10-31 16:45:27
 * @LastEditors: 刘强
 * @Description: In User Settings Edit
 * @FilePath: \Library\src\api\config.ts
 */
import axios from "axios";
import { localeStore } from "../store/local/index";
import Message from "../compontent/comm/message";
import { deleteInvalidParam } from "../util/convert";
import { messageText } from "../constants/index";

/**
 * 主要params参数
 * @params method {string} 方法名
 * @params url {string} 请求地址  例如：/login 配合baseURL组成完整请求地址
 * @params baseURL {string} 请求地址统一前缀 ***需要提前指定***  例如：http://cangdu.org
 * @params timeout {number} 请求超时时间 默认 30000
 * @params params {object}  get方式传参key值
 * @params headers {string} 指定请求头信息
 * @params withCredentials {boolean} 请求是否携带本地cookies信息默认开启
 * @params validateStatus {func} 默认判断请求成功的范围 200 - 300
 * @return {Promise}
 * 其他更多拓展参看axios文档后 自行拓展
 * 注意：params中的数据会覆盖method url 参数，所以如果指定了这2个参数则不需要在params中带入
 */
// 自动更新请求路径
const host = window.location.host;
let herf = "";
switch (host) {
  // 正式
  case "library.wdf.cn":
    herf = "https://library.wdf.cn:7778/";
    break;
  // 测试
  case "library-test.wdf.cn":
    herf = "https://library-test.wdf.cn:7778/";
    break;
  // 开发
  case "library-dev.wdf.cn":
    herf = "https://library-dev.wdf.cn:7778/";
    break;
  //本地
  default:
    herf = "mock";
}

//请求头配置
const $http = axios.create({
  baseURL: herf,
  timeout: 10000,
  headers: {
    "Content-Type": "application/json;charset=UTF-8",
  },
});
// 添加请求拦截器
$http.interceptors.request.use(
  (config: any) => {
    if (localeStore.authorization) {
      config.headers["whale-auth"] = "bearer " + localeStore.authorization;
    }
    if (config.method === "post") {
      config.data = deleteInvalidParam(config.data || {});
    } else {
      config.params = deleteInvalidParam(config.params || {});
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 添加响应拦截器
$http.interceptors.response.use(
  (response) => {
    let { code } = response.data;
    if (code == 401) {
      localeStore.setToken("");
      Message("请先登录!");
      window.location.href = "/";
    }
    return response.data;
  },
  (error) => {
    let param = {
      message: messageText[error.message] ? messageText[error.message] : error,
      code: typeof error.code == "number" ? error.code : 500,
    };
    param = typeof error.code == "number" ? error : param;
    return param;
  }
);

export default $http;
